package flirtme.server;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.widget.Toast;

import com.ans.flirtme.R;
import com.loopj.android.http.RequestParams;

import flirtme.activities.MainMenuActivity;
import flirtme.constants.Constants;
import flirtme.libraries.utils.Utils;
import flirtme.managers.UserManager;
import flirtme.model.CurrentUser;
import flirtme.widgets.NonCancellableProgressDialog;

public class UserProfileServices {
	
	private static final String paramUserName = "username";
	private static final String paramFirstName = "firstName";
	private static final String paramLastName = "lastName";
	private static final String paramEmail = "email";
	private static final String paramBirthdate = "birthDate";
	private static final String paramGender = "gender";
	private static final String paramInterests = "interests";
	private static final String paramImageOUT = "image_base64";
	private static final String paramImageIN = "avatarUrl";
	private static final String genderServerMale="m";
	private static final String genderServerFemale="f";
	
	public static void callEditProfileService(final Context context, Bitmap imageData, String interests) {
		RequestParams params = new RequestParams();
		
		CurrentUser user = UserManager.instance().getUser();

		params.put(paramUserName, user.getUsername());
		
		if (user.getFirstName() != null) 
			params.put(paramFirstName, user.getFirstName());
		
		if (user.getLastName() != null) 
			params.put(paramLastName, user.getLastName());
		
		if (user.getEmail() != null) 
			params.put(paramEmail, user.getEmail());
		
		if (user.getGender() != null) 
			params.put(paramGender, user.getGender());
		
		if (user.getBirthDay() != null) 
			params.put(paramBirthdate, user.getBirthDay());
		
		if (interests != null) 
			params.put(paramInterests, interests);
		
		if (imageData != null){
			String base64ImageData = Utils.encodeTobase64(imageData);
			if (base64ImageData != null)
				params.put(paramImageOUT, base64ImageData);
		}

		callEditProfileService(context, params);
	}

	@SuppressLint("SimpleDateFormat")
	private static String formatBirthDate(Date birthDate) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(Constants.EDIT_PROFILE_INFO_DATE_PATTERN);
		return dateFormat.format(birthDate);
	}

	private static void callEditProfileService(final Context context, RequestParams params) {

		FlirtMeRestClient.post(Constants.EDIT_PROFILE_INFO_SERVICE, params,

		new FlirtMeAsyncHttpResponseHandler(context) {
			NonCancellableProgressDialog dialog = new NonCancellableProgressDialog(
					context);

			@Override
			public void onSuccess(JSONObject response) {
				if (FlirtMeAsyncHttpResponseHandler.isValid(response)) {
					toastMessageWithText(context, R.string.save_user_profile_success);
					
					try {
						JSONObject payload = response.getJSONObject("payload");
						String imageUrl = payload.getString("avatarUrl");
						UserManager.instance().setImageUrl(imageUrl);
						UserManager.instance().saveCurrentUserPreferences(getContext());
						
						Intent intent = new Intent(context, MainMenuActivity.class);
						context.startActivity(intent);
					} catch (JSONException e) {
						e.printStackTrace();
					}
					
					UserManager.instance().setProfileCreated(true);
				} else {
					toastMessageWithText(context, R.string.save_user_profile_fail);
				}
			}

			@Override
			public void onFinish() {
				dialog.dismiss();
			}

			@Override
			public void onStart() {
				toastMessageWithText(context, R.string.save_user_profile_on_start_msg);
			}
		});
	}
	
	public static void callLoadProfileService(final Context context) {
		RequestParams params = new RequestParams();
		
		CurrentUser user = UserManager.instance().getUser();
		params.put(paramUserName, user.getUsername());

		callLoadProfileService(context, params);
	}

	private static void callLoadProfileService(Context context, RequestParams params) {
		FlirtMeRestClient.get(Constants.GET_PROFILE_INFO_SERVICE, params,

		new FlirtMeAsyncHttpResponseHandler(context) {
			NonCancellableProgressDialog dialog = new NonCancellableProgressDialog(context);
			
			@Override
			public void onSuccess(JSONObject response) {
				if (FlirtMeAsyncHttpResponseHandler.isValid(response)) {
					this.parseResponse (response, context);
					toastMessageWithText(context, R.string.load_user_profile_success);
				} else {					
					toastMessageWithText(context, R.string.load_user_profile_fail);
				}
			}

			private void parseResponse(JSONObject response, Context context) {

					try {
						CurrentUser user = UserManager.instance().getUser();
						JSONObject payload = response.getJSONObject(Constants.PAYLOAD);
						
						user.setFirstName(payload.getString(paramFirstName));
						user.setLastName(payload.getString(paramLastName));
						user.setEmail(payload.getString(paramEmail));
						user.setGender(getGender(payload.getString(paramGender)));
						user.setAvatarUrl( payload.getString(paramImageIN) );

						UserManager.instance().setProfileLoaded(true);
					} catch (JSONException e) {
						e.printStackTrace();
					}
			}

			@Override
			public void onFinish() {
				dialog.dismiss();
			}

			@Override
			public void onStart() {
				dialog.setMessage(context.getString(R.string.calling_load_profile_dialog_msg));
				dialog.show();

			}
		});
		
	}
	
	private static String getGender(String genderServerRespose) {
		if (genderServerMale.equals(genderServerRespose)) {
			return Constants.GENDER_MALE;
		} else if (genderServerFemale.equals(genderServerRespose)) {
			return Constants.GENDER_FEMALE;
		} else {
			return Constants.GENDER_UNDEFINED;
		}
	}

	private static void toastMessageWithText(Context context, int text) {
		Toast.makeText(context, text, Toast.LENGTH_LONG).show();
	}

}
